<?php
/**
 * Create by 11li
 * Date 2020/2/20
 * Time 16:52
 *
 */

namespace app\common\service;


use app\common\model\Commission;
use app\common\model\Funds;
use app\common\model\Promoter;
use app\common\model\User;
use think\Db;
use think\Exception;

class FundsService extends BaseService
{
	
	public function __construct()
	{
		$this->model = new Funds();
	}
	
	public function getUserCommissionList($userId, $page, $status)
	{
		$where = [
			'c.user_id' => $userId,
			'c.status' => $status
		];
		
		$total = Db::name('commission')->alias('c')
			->where($where)
			->count();
		$list = [];
		
		if($total > 0 ) {
			$list = Db::name('commission')->alias('c')
				->join('order o', 'c.order_id = o.id', 'left')
				->join('goods g', 'c.goods_id = g.id', 'left')
				->where($where)
				->order(['c.create_time' => 'desc'])
				->page($page)
				->field('c.id, c.amount, o.order_no, from_unixtime(c.create_time) as date, g.goods_name, c.type')
				->select();
			
			if($list) {
				$typeList = StatusService::$commissionTypeList;
				foreach ($list as &$item) {
					$item['type_text'] = $typeList[$item['type']] ??'';
				}
			}
		}
		
		return [
			'total' => $total,
			'list' => $list,
			'page' => $page
		];
	}
	
	/**
	 * 添加流水记录
	 * @param $userId 用户ID
	 * @param $amount 金额
	 * @param float|int $beforeAmount 变动前金额
	 * @param $accountType 帐户类型
	 * @param $operationType 操作类型
	 * @param $type 类型
	 * @param string $orderId 订单ID
	 * @param string $remark 备注
	 * @param int $relation_user_id 相关用户ID
	 * @return bool
	 */
	public function addRecord($userId, $amount, $beforeAmount, $accountType, $operationType, $type, $orderId = '', $remark="", $relation_user_id=''){
		$data = [
			'user_id' => $userId,
			'amount' => $amount,
			'before' => $beforeAmount,
			'account_type' => $accountType,
			'operation_type' => $operationType,
			'type' => $type,
			'order_id' => $orderId,
			'remark' => $remark,
			'create_time' => time(),
			'relation_user_id' => $relation_user_id
		];
		$res = $this->model->insert($data);
		if($res){
			//添加信息
			return true;
		}
		return false;
	}
	
	public function sendCommission($id)
	{
		$where = ['order_id' => $id, 'status' => StatusService::COMMISSION_STATUS_WAIT];
		
		$model = new Commission();
		$rows = $model
			->where($where)
			->select();
		
		if($rows) {
			//更改状态
			$statusRes = $model
				->save(['status' => StatusService::COMMISSION_STATUS_SEND], $where);
			if(!$statusRes) {
				$this->error = '更改佣金状态出错';
				return false;
			}
			
			$fundsObj = new FundsService();
			
			$sendCommission = 0;
			foreach ($rows as $row) {
				$user = User::get($row['user_id']);
				
				//添加资金记录
				$fundsRes = $fundsObj->addRecord($row['user_id'], $row['amount'], $user['money'], Funds::ACCOUNT_TYPE_BALANCE, Funds::OPE_TYPE_PLUS, Funds::TYPE_REBATE, $row['order_id'], '', $row['relation_user_id']);
				if(!$fundsRes) {
					$this->error = '添加资金记录出错';
					return false;
				}
				
				$userRes = Db::name('user')
					->where(['id' => $row['user_id']])
					->setInc('money', $row['amount']);
				if(!$userRes) {
					$this->error = '添加余额出错';
					return false;
				}
				
				$sendCommission += $row['amount'];
			}
			
			//更改代理冻结佣金和到账佣金
			if($sendCommission > 0) {
				Db::name('promoter')
					->where('user_id', $rows[0]['user_id'])
					->inc('commission', $sendCommission)
					->dec('disabled_commission', $sendCommission)
					->update(['update_time' => time()]);
				
			}
		}
		
		return true;
	}
}